<template>
  <el-card>
    <template #header><h2>护理项目管理</h2></template>

    <el-form :inline="true" :model="filters" class="toolbar">
      <el-form-item label="名称">
        <el-input v-model="filters.name" placeholder="输入名称" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filters.status" placeholder="全部">
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchProjects">查询</el-button>
        <el-button @click="openAddDialog">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="projects" stripe>
      <el-table-column prop="code" label="编号" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="cycle" label="执行周期" />
      <el-table-column prop="times" label="执行次数" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'warning'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page.current"
      :page-size="page.size"
      :total="page.total"
      @current-change="fetchProjects"
    />

    <!-- Add/Edit Dialog -->
    <el-dialog
      :title="editRow ? '编辑项目' : '添加项目'"
      v-model="dialogVisible"
    >
      <el-form :model="formData" label-width="80px">
        <el-form-item label="编号">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="formData.price" />
        </el-form-item>
        <el-form-item label="周期">
          <el-input v-model="formData.cycle" />
        </el-form-item>
        <el-form-item label="次数">
          <el-input-number v-model="formData.times" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProject">确认</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch } from 'vue'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'

const axios = inject('axios')
const filters = reactive({ name: '', status: null })
const projects = ref([])
const page = reactive({ current: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const formData = reactive({
  id: null,
  code: '',
  name: '',
  price: 0,
  cycle: '',
  times: 1,
  description: '',
  status: 1
})
const editRow = ref(null)

// 1. 拉列表
async function fetchProjects() {
  const resp = await axios.get('/CareProjectController/queryByStatus', {
    params: {
      name: filters.name,
      status: filters.status,
      cur: page.current,
      number: page.size
    }
  })
  projects.value = resp.data.data
  page.total = resp.data.total
}

// 2. 新增
function openAddDialog() {
  editRow.value = null
  Object.assign(formData, {
    id: null,
    code: '',
    name: '',
    price: 0,
    cycle: '',
    times: 1,
    description: '',
    status: 1
  })
  dialogVisible.value = true
}

// 3. 编辑
function openEditDialog(row) {
  editRow.value = row
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 4. 保存（新增或更新）
//    如果是更新且 status=0，会自动触发后端清理关联
async function saveProject() {
  const url = editRow.value
    ? '/CareProjectController/updateCareProject'
    : '/CareProjectController/addCareProject'

  // 如果是更新 & 由启用变为停用，先确认
  if (
    editRow.value &&
    editRow.value.status === 1 &&
    formData.status === 0
  ) {
    const ok = await ElMessageBox.confirm(
      '您将停用此项目，所有级别中的对应记录将被移除，确认继续？',
      '警告',
      { type: 'warning' }
    ).catch(() => false)
    if (!ok) return
  }

  await axios.post(url, qs.stringify(formData))
  dialogVisible.value = false
  fetchProjects()
}

// 5. 删除（逻辑删除 & 清除关联）
async function confirmDelete(row) {
  const ok = await ElMessageBox.confirm(
    '删除后项目将隐藏，且所有级别中的对应记录将被移除，确认删除？',
    '提示'
  ).catch(() => false)
  if (!ok) return

  await axios.post(
    '/CareProjectController/deleteCareProject',
    qs.stringify({ id: row.id })
  )
  fetchProjects()
}

onMounted(fetchProjects)
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}
</style>
